import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wu_you/state/cubit/basic_cubit.dart';

typedef ErrorWidgetBuilder = Function();

class CountdownView extends StatefulWidget {
  CountdownView({
    Key key,
    @required this.hint,
    @required this.onPressed,
    this.second = 60,
  })  : assert(hint != null),
        assert(onPressed != null),
        super(key: key);

  ///提示
  final Widget hint;

  ///倒计时时间
  final int second;

  ///点击事件
  final VoidCallback onPressed;

  @override
  CountdownViewState createState() => CountdownViewState();
}

class CountdownViewState extends State<CountdownView> {
  Timer _timer;
  IntCubit _cubit = IntCubit();

  @override
  void initState() {
    super.initState();
  }

  set state(CountdownState state) {
    switch (state) {
      case CountdownState.init:
        _doInit();
        break;
      case CountdownState.loading:
        _doLoading();
        break;
      case CountdownState.countdown:
        _doCountdown();
        break;
    }
  }

  void _doInit() {
    _cubit.value = 0;
    _timer?.cancel();
    _timer = null;
  }

  void _doLoading() {
    _cubit.value = widget.second + 1;
  }

  void _doCountdown() {
    if (_timer == null) {
      _timer = Timer.periodic(Duration(seconds: 1), (timer) {
        var value = widget.second - timer.tick;
        if (value == 0) {
          _doInit();
        } else {
          _cubit.value = value;
        }
      });
    }
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (BuildContext context) => _cubit,
      child: BlocBuilder<IntCubit, int>(
        builder: (BuildContext context, int state) {
          Widget child;
          if (state == widget.second + 1) {
            child = CircularProgressIndicator(strokeWidth: 2);
          }
          if (state > 0 && state <= widget.second) {
            child = Text("${state}S");
          }
          if (child == null) {
            child = InkWell(
              onTap: widget.onPressed,
              child: widget.hint,
            );
          }
          return Center(
            child: child,
          );
        },
      ),
    );
  }
}

enum CountdownState { init, loading, countdown }
